package com.ayf.payment.game.api.service.payment;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.channel.xingyou.util.XingYouSignUtil;
import com.ayf.payment.game.api.dto.MerchantCommonDTO;
import com.ayf.payment.game.api.dto.OrderAndMerchantDTO;
import com.ayf.payment.game.api.dto.platform.MerchantPaymentProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.type.OrderStatus;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


@Service
public class XingYouPaymentService extends IPaymentService {

    @Override
    public Map<String, Object> paymentUtil(Order order, Partition partition, String orderCreateStr, String traceId, String redirectUrl) {
        Map<String, Object> map=new HashMap<>();
        MerchantPaymentProductDTO merchantPaymentProductDTO = systemInitialization.productDTO(order.getPayTypeId());
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(merchantPaymentProductDTO.getcId());
        MerchantCommonDTO merchantDTO = merchantService.getMerchantCommon(partition.getMerchantId());
        String qq = "";
        if (StringUtils.isNotBlank(merchantDTO.getCustomerQq())) {
            qq = merchantDTO.getCustomerQq();
        } else if (StringUtils.isNotBlank(merchantDTO.getQq())) {
            qq = merchantDTO.getQq();
        }
        String produceName = String.format("查单QQ:%s充值账号:%s订单号:%s",qq,order.getRechargeNumber(),order.getMerchantOrderNo());
        String productDesc = order.getRechargeNumber();
        BigDecimal actualOrderAmt = getActualOrderAmt(order.getAmount(),paymentChannelDTO.getId(),partition.getMerchantId());
        BaseResData baseResData = orderCreate(traceId,order,paymentChannelDTO,merchantPaymentProductDTO.getBusinessCode(),produceName,productDesc,redirectUrl,actualOrderAmt);
        String orderCreateUrl = "";
        if (baseResData.isProcessing()){
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 星游下单失败 请求接口成功，接口响应超时", traceId, order.getMerchantId(), order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (baseResData.isSuccess()) {
            String rpsData = baseResData.getData();
            JSONObject jsonData = JSONObject.parseObject(rpsData);
            String retCode = jsonData.getString("retCode");
            if ("SUCCESS".equals(retCode)){
                JSONObject payParamsJson =  jsonData.getJSONObject("payParams");
                if (payParamsJson == null){
                    LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 星游下单失败 请求接口成功，接口返回报文 payParams为空",traceId,order.getMerchantId(), order.getMerchantOrderNo());
                    throw new NullSetException(traceId + "下单失败，请稍后重试！");
                }
                String payOrderId = jsonData.getString("payOrderId");
                order.setOrderNo(payOrderId);
                orderCreateUrl = payParamsJson.getString("payUrl");
                if (StringUtils.isEmpty(orderCreateUrl)){
                    LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 星游下单失败 请求接口成功，接口返回报文 payUrl为空",traceId,order.getMerchantId(), order.getMerchantOrderNo());
                    throw new NullSetException(traceId + "下单失败，请稍后重试！");
                }
            } else {
                String retMsg = jsonData.getString("retMsg");
                LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 星游下单失败 请求接口成功，接口返回失败 retCode:{} retMsg:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),retCode,retMsg);
                throw new NullSetException(traceId + "下单失败，请稍后重试！");
            }
        } else {
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 星游下单失败 请求接口失败 retCode:{} retMsg:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),baseResData.getRespCode(),baseResData.getRespMsg());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        LogPortal.info("{} 商户ID[{}] 商户订单号[{}] 星游下单 通道支付URL[{}]", traceId, order.getMerchantId(), order.getMerchantOrderNo(),orderCreateUrl);
        order.setRandomAmt(BigDecimal.ZERO);
        order.setPayChannleName(paymentChannelDTO.getName());
        order.setPayChannleId(paymentChannelDTO.getId());
        order.setPayTypeId(merchantPaymentProductDTO.getProductId());
        order.setPayTypeName(merchantPaymentProductDTO.getProductName());
        order.setMerchantIncome(BigDecimal.ZERO);
        order.setPlatformIncome(BigDecimal.ZERO);
        order.setFee(BigDecimal.ZERO);
        order.setChannelIncome(BigDecimal.ZERO);
        orderMapper.insertSelective(order);
        map.put("code", "003");
        map.put("RedirectUrl",orderCreateUrl);
        return map;
    }


    private BaseResData orderCreate(String traceId,Order order,PaymentChannelDTO paymentChannelDTO,String businessCode,String produceName,String productDesc,String redirectUrl,BigDecimal actualOrderAmt){
        String methodName = "星游下单";
        String KeyValue = paymentChannelDTO.getChannelKey();
        String parter = paymentChannelDTO.getAccountNumber();
        String appId = paymentChannelDTO.getChannelPublicKey();
        String returnUrl=paymentChannelDTO.getReturnUrl();
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道下单地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("api/pay/create_order");
        if (StringUtils.isEmpty(returnUrl)){
            LogPortal.error("{} 失败，异步通知地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!returnUrl.endsWith("/")){
            returnUrl=returnUrl.concat("/");
        }

        if (!redirectUrl.endsWith("/")){
            redirectUrl=redirectUrl.concat("/");
        }

        Map<String,String> reqParam = new TreeMap<>();
        reqParam.put("appId",appId);
        reqParam.put("productId",getPayCode(businessCode));
        reqParam.put("notifyUrl",returnUrl.concat("gameapip/v/xingyou/pay/notify"));
        reqParam.put("amount",String.valueOf(BigDecimalUtil.yuanToFen(actualOrderAmt)));
        reqParam.put("returnUrl",redirectUrl.concat("gws/loading.html?orderNo=").concat(order.getMerchantOrderNo()));
        reqParam.put("mchOrderNo",order.getMerchantOrderNo());
        reqParam.put("mchId",parter);
        reqParam.put("currency","cny");
        reqParam.put("clientIp","");
        reqParam.put("device","");
        reqParam.put("subject",produceName);
        reqParam.put("body",productDesc);
        reqParam.put("param1","");
        reqParam.put("param2","");
        reqParam.put("extra","");

        String sign= XingYouSignUtil.getSign(traceId,methodName,reqParam,KeyValue);
        reqParam.put("sign",sign);
        BaseResData baseResData = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return baseResData;
    }


    @Override
    public void queryPayOrder(OrderAndMerchantDTO dto, String traceId) {
        String methodDesc = "星游订单查询";
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(dto.getPayChannleId());
        BaseResData baseResData = orderQuery(traceId,methodDesc,paymentChannelDTO,dto);
        if (baseResData.isProcessing()){
            return;
        }
        if (baseResData.isSuccess()){
            String result = baseResData.getData();
            JSONObject jsonData = JSONObject.parseObject(result);
            String code = jsonData.getString("retCode");
            if ("SUCCESS".equals(code)){
                String status = jsonData.getString("status"); // 订单状态
                if (StringUtils.isEmpty(status) || "0".equals(status)||"1".equals(status)){
                    return;
                }
                String merchantOrderNo = jsonData.getString("mchOrderNo"); // 商户订单号
                String channelOrderNo = jsonData.getString("payOrderId"); // 支付接口订单号
                Order order = orderService.selectByMerchantOrderNo(merchantOrderNo);
                if (order == null) {
                    LogPortal.error("{} {} 商户订单号[{}]在我方系统查询不到", traceId,methodDesc,merchantOrderNo);
                    return;
                }
                OrderStatus orderStatus= OrderStatus.PROCESSING;
                if ("2".equals(status) || "3".equals(status)){ // 成功
                    orderStatus= OrderStatus.SUCCESS;
                }
                if (OrderStatus.PROCESSING.equals(order.getOrderStatus()) && !orderStatus.equals(OrderStatus.PROCESSING)) {
                    order.setOrderStatus(orderStatus);
                    order.setChannelRpsMsg("支付成功");
                    if (StringUtils.isNotEmpty(channelOrderNo)){
                        order.setOrderNo(channelOrderNo);
                    }
                    orderService.paymentOrder(order, new JSONObject());
                    if (OrderStatus.SUCCESS.equals(order.getOrderStatus())) {
                        orderService.orderToGetWay(order);
                        wxSendMsgUtils.rechargeSuccess(order);
                    }
                }
            } else {
                String message = jsonData.getString("retMsg").concat(jsonData.getString("data"));
                LogPortal.error("{} {} 查询通道返回错误码:{} 错误描述:{}",traceId,methodDesc,code,message);
            }
        }
    }

    private BaseResData orderQuery(String traceId,String methodName,PaymentChannelDTO paymentChannelDTO,OrderAndMerchantDTO dto){
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        String orderNo = dto.getMerchantOrderNo();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道订单查询地址不能为空，订单号:{}",traceId,dto.getMerchantOrderNo());
            throw new NullSetException(traceId + "订单查询失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("api/pay/query_order");

        Map<String,String> reqParam = new TreeMap<>();
        reqParam.put("appId",paymentChannelDTO.getChannelPublicKey());
        reqParam.put("executeNotify","false");
        reqParam.put("mchId",paymentChannelDTO.getAccountNumber());
        reqParam.put("mchOrderNo",orderNo);

        String sign =XingYouSignUtil.getSign(traceId,methodName,reqParam,paymentChannelDTO.getChannelKey());
        reqParam.put("sign",sign);
        BaseResData result = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return result;
    }

    private String getPayCode(String code){
        if("ALIPAY".equals(code)||"ANTCREDITPAY".equals(code)){
            return "8006";
        } else if("WECHAT".equals(code)){
            return "8002";
        } else if("UNIONSCANPAY".equals(code)){
            return "8014";
        } else {
            throw new NullSetException("该通道不支持充值，请更换其他通道充值！");
        }
    }

    private static void testOrderCreate(){
        PaymentChannelDTO paymentChannelDTO = getTestPaymentChannelDTO();
        String businessCode = "ALIPAY";// 支付宝
//        String businessCode = "WECHAT";// 微信
        Order order = new Order();
        Date currentDate = DateUtils.getNowDate();
        String orderCreateStr = DateUtils.dateToString(currentDate, DateUtils.formatPattern_full_03);
        String orderNo = "M" + orderCreateStr + SnowFlakeUtils.getUniqueId();
        order.setMerchantOrderNo(orderNo);
        order.setCreateTime(currentDate);
        order.setAmount(BigDecimal.valueOf(1));
        order.setMerchantId(1000);
        String traceId = SnowFlakeUtils.getTraceId28();
        String redirectUrl = "http://uatxy.xyouplay.com";
        BigDecimal orderAmt = BigDecimal.valueOf(1);
        XingYouPaymentService xinYou2PaymentService = new XingYouPaymentService();
        BaseResData baseResData = xinYou2PaymentService.orderCreate(traceId,order,paymentChannelDTO,businessCode,"01区元宝","2323",redirectUrl,orderAmt);
        System.out.println("星游下单返回报文:"+JSONObject.toJSONString(baseResData));
    }


    private static void testOrderQuery(){
        PaymentChannelDTO paymentChannelDTO = getTestPaymentChannelDTO();
        String traceId = SnowFlakeUtils.getTraceId28();

        OrderAndMerchantDTO dto = new OrderAndMerchantDTO();
        dto.setMerchantId(1000);
        dto.setMerchantOrderNo("M".concat(traceId));
        XingYouPaymentService xinYou2PaymentService = new XingYouPaymentService();
        BaseResData result = xinYou2PaymentService.orderQuery(traceId,"星游订单查询",paymentChannelDTO,dto);
        System.out.println("星游订单查询返回结果:"+result);
    }


    private static PaymentChannelDTO getTestPaymentChannelDTO(){
        PaymentChannelDTO paymentChannelDTO = new PaymentChannelDTO();
        paymentChannelDTO.setPaymentUrl("http://awg.525pay.com/");
        paymentChannelDTO.setReturnUrl("http://uatxy.xyouplay.com");
        paymentChannelDTO.setChannelKey("UK74KVELH6XCAVPQLQWASVCVVOA0XCBFTB2OOC1MT6UEQOQZBBQAESOLPWICO1513PN881T0OS7TBQRT8VYK2VBNSL4KUCSMFNDRUQ3SUBB5OJTMMZOSUWL4ZY22FXCE");
        paymentChannelDTO.setAccountNumber("20000010");// 商户ID
        paymentChannelDTO.setChannelPublicKey("fd6f35e9201340649e70933c6360e2c7");// appId
        return paymentChannelDTO;
    }

    public static void main(String[] args) {
//        testOrderCreate();
        testOrderQuery();
    }

}
